<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
$exc = new exchange($ecs->table('store'), $db, 'id', 'name');

if ($_REQUEST['act'] == 'baidu_map'){
	$id = $_GET['id'];
	if($id != ""){
		$sql = "SELECT * FROM " . $ecs->table('store') . " WHERE id = '$id'";
        $store = $db->getRow($sql);
		$smarty->assign('coordinates',$store['lng'].','.$store['lat']);
	}
	$smarty->display('rg_baidu_map.htm');
}elseif ($_REQUEST['act'] == 'api_area'){
    include(ROOT_PATH.'includes/cls_json.php');
    $json   = new JSON;
	$id		= !empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	$level	= !empty($_REQUEST['level']) ? intval($_REQUEST['level']) : 0;
	$res = get_regions($level, $id);
	die($json->encode($res));
}
/*------------------------------------------------------ */
//-- 店铺列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    $smarty->assign('ur_here',      "店铺列表");
    $smarty->assign('action_link',  array('text' => "添加店铺", 'href' => 'rg_storelist.php?act=add'));
    $smarty->assign('full_page',    1);

    $store_list = get_dianlist();
    $smarty->assign('store_list',  $store_list['store']);
    $smarty->assign('filter',       $store_list['filter']);
    $smarty->assign('record_count', $store_list['record_count']);
    $smarty->assign('page_count',   $store_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($store_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->display('rg_store_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $store_list = get_dianlist();
    $smarty->assign('store_list',  $store_list['store']);
    $smarty->assign('filter',       $store_list['filter']);
    $smarty->assign('record_count', $store_list['record_count']);
    $smarty->assign('page_count',   $store_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($store_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('rg_store_list.htm'), '',
        array('filter' => $store_list['filter'], 'page_count' => $store_list['page_count']));
}

/*------------------------------------------------------ */
//-- 列表页编辑名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_name')
{
    check_authz_json('store_manage');

    $id     = intval($_POST['id']);
    $name   = json_str_iconv(trim($_POST['val']));

    /* 检查名称是否重复 */
    if ($exc->num("name", $name, $id) != 0)
    {
        make_json_error(sprintf($_LANG['storename_exist'], $name));
    }
    else
    {
        if ($exc->edit("name = '$name'", $id))
        {
            admin_log($name, 'edit', 'store');
            clear_cache_files();
            make_json_result(stripslashes($name));
        }
        else
        {
            make_json_result(sprintf($_LANG['storeedit_falure'], $name));
        }
    }
}

/*------------------------------------------------------ */
//-- 删除店铺
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('store_manage');

    $id = intval($_GET['id']);
    $name = $exc->get_name($id);
    $exc->drop($id);

    /* 更新店铺 */
    $table_array = array('products','order_goods','cart');
    foreach ($table_array as $value)
    {
        $sql = "UPDATE " . $ecs->table($value) . " SET id = 0 WHERE id = '$id'";
        $db->query($sql);
    }

    /* 记日志 */
    admin_log($name, 'remove', 'store');

    /* 清除缓存 */
    clear_cache_files();

    $url = 'rg_storelist.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg($_LANG['no_record_selected']);
    }
    else
    {
        /* 检查权限 */
        admin_priv('store_manage');

        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $ecs->table('store') . " WHERE id " . db_create_in($ids);
            $db->query($sql);

            /* 更新店铺 */
            $table_array = array('products','order_goods','cart');
            foreach ($table_array as $value){
                $sql = "UPDATE " . $ecs->table($value) . " SET id = 0 WHERE id " . db_create_in($ids) . " ";
                $db->query($sql);
            }

            /* 记日志 */
            admin_log('', 'batch_remove', 'store');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg($_LANG['batch_drop_ok']);
        }
    }
}

/*------------------------------------------------------ */
//-- 添加、编辑店铺
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('store_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add';
    $smarty->assign('form_action', $is_add ? 'insert' : 'update');

    /* 初始化、取得店铺信息 */
    if ($is_add){
		/* 创建 html editor */
		create_html_editor('FCKeditor1');

        $store = array();
    }else{
        if (empty($_GET['id'])){
            sys_msg('invalid param');
        }

        $id = $_GET['id'];
        $sql = "SELECT * FROM " . $ecs->table('store') . " WHERE id = '$id'";
        $store = $db->getRow($sql);
        if (empty($store)){
            sys_msg('store does not exist');
        }

		/* 创建 html editor */
		create_html_editor('FCKeditor1',htmlspecialchars($store['content']));
    }

    $smarty->assign('store', $store);

    /* 取得地区 */
	$sql = "SELECT * FROM " . $ecs->table('region') . " WHERE parent_id = '1'";
    $regionlist = $db->getAll($sql);
	$smarty->assign('regionlist',$regionlist);

    /* 显示模板 */
    if ($is_add){
        $smarty->assign('ur_here', "添加店铺");
    }else{
        $smarty->assign('ur_here', "编辑店铺");
    }
    if ($is_add){
        $href = 'rg_storelist.php?act=list';
    }else{
        $href = 'rg_storelist.php?act=list&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => $_LANG['store_list']));
    assign_query_info();
    $smarty->display('rg_store_info.htm');
}

/*------------------------------------------------------ */
//-- 提交添加、编辑店铺
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('store_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';

	$coo_arr = explode(',',$_POST['coordinates']);
	$_POST['lng'] = $coo_arr[0] > 0 ? $coo_arr[0] : '';
	$_POST['lat'] = $coo_arr[1] > 0 ? $coo_arr[1] : '';

    /* 判断名称是否重复 */
    if (!$exc->is_only('name', $store['name'], $store['id']))
    {
        sys_msg($_LANG['storename_exist']);
    }

	if (isset($_FILES['store_img']['error'])) // php 4.2 版本才支持 error
    {
        // 最大上传文件大小
        $php_maxsize = ini_get('upload_max_filesize');
        $htm_maxsize = '2M';

        // 商品图片
        if ($_FILES['store_img']['error'] == 0)
        {
            if (!$image->check_img_type($_FILES['store_img']['type']))
            {
                sys_msg("图片格式不正确！", 1, array(), false);
            }
        }
        elseif ($_FILES['goods_img']['error'] == 1)
        {
            sys_msg(sprintf("图片文件太大了（最大值：%s），无法上传。", $php_maxsize), 1, array(), false);
        }
        elseif ($_FILES['goods_img']['error'] == 2)
        {
            sys_msg(sprintf("图片文件太大了（最大值：%s），无法上传。", $htm_maxsize), 1, array(), false);
        }
    }
    /* 4.1版本 */
    else
    {
        // 商品图片
        if ($_FILES['store_img']['tmp_name'] != 'none')
        {
            if (!$image->check_img_type($_FILES['store_img']['type']))
            {

                sys_msg("图片格式不正确！", 1, array(), false);
            }
        }
    }

	if ($_FILES['store_img']['tmp_name'] != '' && $_FILES['store_img']['tmp_name'] != 'none')
    {
        if ($_REQUEST['id'] > 0)
        {
            /* 删除原来的图片文件 */
            $sql = "SELECT store_img FROM " . $ecs->table('store') . " WHERE id = '$_REQUEST[id]'";
            $row = $db->getRow($sql);
            if ($row['store_img'] != '' && is_file('../' . $row['store_img']))
            {
                @unlink('../' . $row['store_img']);
            }
        }

        $store_img      = $image->upload_image($_FILES['store_img']);
		if ($store_img === false)
        {
            sys_msg($image->error_msg(), 1, array(), false);
        }
    }

    /* 提交值 */
    $store = array(
        'id'			=> intval($_POST['id']),
        'name'			=> sub_str($_POST['name'], 255, false),
        'phone'			=> $_POST['phone'],
        'qq'			=> $_POST['qq'],
        'address'		=> $_POST['address'],
        'worktime'		=> $_POST['worktime'],
        'updatetime'	=> time(),
        'content'		=> $_POST['FCKeditor1'],
        'lng'			=> $_POST['lng'],
        'lat'			=> $_POST['lat'],
        'id_province'   => $_POST['id_province'],
        'id_city'		=> $_POST['id_city'],
        'id_dist'		=> $_POST['id_dist'],
        'store_img'		=> $store_img,
    );

    /* 保存店铺信息 */
    if ($is_add){
		$store['addtime'] = time();
        $db->autoExecute($ecs->table('store'), $store, 'INSERT');
        $store['id'] = $db->insert_id();
    }else{
        $db->autoExecute($ecs->table('store'), $store, 'UPDATE', "id = '$store[id]'");
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log($store['name'], 'add', 'store');
    }
    else
    {
        admin_log($store['name'], 'edit', 'store');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'rg_storelist.php?act=add', 'text' => '继续添加店铺'),
            array('href' => 'rg_storelist.php?act=list', 'text' => '返回店铺列表')
        );
        sys_msg('成功添加店铺', 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'rg_storelist.php?act=list&' . list_link_postfix(), 'text' => '返回店铺列表')
        );
        sys_msg('成功编辑店铺', 0, $links);
    }
}

/**
 * 取得店铺列表
 * @return  array
 */
function get_dianlist()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('store');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('store') . " ORDER BY $filter[sort_by] $filter[sort_order]";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
	while ($rows = $GLOBALS['db']->fetchRow($res)){
		$id_province = $GLOBALS['db']->getOne("SELECT region_name FROM " . $GLOBALS['ecs']->table('region') . " where region_id = '".$rows['id_province']."'");
		$id_city = $GLOBALS['db']->getOne("SELECT region_name FROM " . $GLOBALS['ecs']->table('region') . " where region_id = '".$rows['id_city']."'");
		$id_dist = $GLOBALS['db']->getOne("SELECT region_name FROM " . $GLOBALS['ecs']->table('region') . " where region_id = '".$rows['id_dist']."'");
		$rows['rg_add'] = $id_province.$id_city.$id_dist;
        $arr[] = $rows;
    }

    return array('store' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

?>